﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.AnalysisTools;

using esri.ParaSeting;
using esri.DataBase;
using esri.Detect;
using esri1.FieldInitial;
using esri_field.Field_Calculation;


namespace esri
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void 参数设置_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.Owner = this;
            form2.Initialize();
            form2.Show();
        }

        public TabControl tabcontrol
        {
            get { return tabControl1; }
            set { tabControl1 = value; }
        }

        public void Initialize()
        {
            this.tabControl1.Enabled = false;
        }


        
        


        struct PointStruct
        {
            public double x ;
            public double y ;
        }
        PointStruct[] ptArray;

        private void button1_Click(object sender, EventArgs e)
        {
            ///
            ///添加初始格子图层
            ///各自图层不予以显示
            ILayer pLayer;
      //      axMapControl1.AddShapeFile(@"F:\study\大坝填筑碾压质量评价系统\图层数据", "7372_Shapefile.shp");
            pLayer = axMapControl1.get_Layer(0);
         //   pLayer.Visible = false;

            //给格子图层增加属性便于之后的显示
            IWorkspaceFactory pWorkSpaceFactory = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace pFeatureWorkSpace = pWorkSpaceFactory.OpenFromFile(@"D:\esri000", 0) as IFeatureWorkspace;
            IFeatureClass pFeatureClass = pFeatureWorkSpace.OpenFeatureClass("MainGrid");

            IField pField = new FieldClass();
            IFieldEdit pFieldEdit = pField as IFieldEdit;

            pFieldEdit.Name_2 = "超速次数";
            pFieldEdit.DefaultValue_2 = "1";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFeatureClass.AddField(pField);

            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            pFieldEdit.DefaultValue_2 = 0;
            pFieldEdit.Name_2 = "偏向次数";
            pFeatureClass.AddField(pField);

            Paraseting PS=Paraseting.Instance();    
            string strResultTableName;
            strResultTableName = "select * from dbo.GPSTBL_SD_" + PS.UnitNo.Insert(4, "_"); 
            DBConnection DBC = DBConnection.Instance();
            DBOperation DBO = new DBOperation();
            DBO.ConnectionString = DBC.ConnectionString;
            SqlConnection conn = DBO.Connect();
  //          try
  //          {
  //              SqlCommand myCommand = new SqlCommand(strResultTableName, conn); 
  //              SqlDataReader DataReader = myCommand.ExecuteReader();
  //              MessageBox.Show("存在结果表，请直接点击查看结果");
  //          }
  //          catch
           {
                MessageBox.Show("no result please wait……");
                string strTableName = "select * from dbo.TABLE_NY_RESULT";
                SqlCommand myCommand = new SqlCommand(strTableName, conn);
                SqlDataReader DataReader = myCommand.ExecuteReader();
                int iIndex = 0;
                //得到数据表中的行数
                DBOperation dbo = new DBOperation();
                dbo.ConnectionString = DBC.ConnectionString;
                SqlConnection countconn = dbo.Connect();
                string sqlCount = "select count(*) from dbo.TABLE_NY_RESULT";
                int iGridCount = dbo.GetRowCount(sqlCount);
                dbo.CloseConnection();
                //初始化格子数据，用数组保存，包括了FID X Y坐标
                SpeedDirectionDetect SDDetect = new SpeedDirectionDetect(iGridCount);
                while (DataReader.Read())
                {
                    SDDetect.InitializeGrid(DataReader.GetValue(0).ToString(), Convert.ToDouble(DataReader.GetValue(1)), Convert.ToDouble(DataReader.GetValue(2)), Convert.ToInt32(DataReader.GetValue(0)));                
                }
                DBO.CloseConnection();
                //
                DBO = new DBOperation();
                DBO.ConnectionString = DBC.ConnectionString;
                conn = DBO.Connect();
                //初始化处理二号车采集的数据
                string strTableCar = "select * from dbo.TBLGPSDATA_1000_133_" + PS.UnitNo + "_2";
                string strCarNo = "2";
                dbo = new DBOperation();
                dbo.ConnectionString = DBC.ConnectionString;
                dbo.Connect();
                int iPointCount = dbo.GetRowCount("select count(*) from dbo.TBLGPSDATA_1000_133_" + PS.UnitNo + "_2");
                dbo.CloseConnection();

                ptArray=new PointStruct[iPointCount];
                myCommand = new SqlCommand(strTableCar, conn);
                DataReader = myCommand.ExecuteReader();

                //统计计算所需的时间
                int ipointcount=1; int a = Environment.TickCount;

                while(DataReader.Read())
                {
                    if ((Math.Abs(Convert.ToDouble(DataReader.GetValue(DataReader.GetOrdinal("LON"))) - ptArray[ipointcount-1].x) < 0.1) && (Math.Abs(Convert.ToDouble(DataReader.GetValue(DataReader.GetOrdinal("LAT"))) - ptArray[ipointcount-1].y) < 0.1))
                    {}
                    else
                    {
                        ptArray[ipointcount].x = Convert.ToDouble(DataReader.GetValue(DataReader.GetOrdinal("LON")));
                        ptArray[ipointcount].y = Convert.ToDouble(DataReader.GetValue(DataReader.GetOrdinal("LAT")));
                        ipointcount++; 
                    }
                }
                //diao yong han shu shi xian 
                //SDDetect.SpeedDirectionCalculate(ptArray,PS.MaxSpeed,PS.MinSpeed,PS.RollDirection,PS.AngleError);
                //开始计算
                Form5 form5=new Form5();
                form5.Show();
                form5.progressBar1.Maximum = ipointcount ;
                for(int i=0;i<ipointcount-1;i++)
                {
                    form5.progressBar1.Value = i;
                    System.Diagnostics.Trace.WriteLine(i);
                    double tempSpeed;
                    double tempDirection;
                    double tempCos = Math.Cos(PS.RollDirection);
                    double tempSin = Math.Sin(PS.RollDirection);
                    double tempError;
                    tempSpeed = Math.Sqrt(Math.Pow((ptArray[i + 1].x - ptArray[i].x), 2) + Math.Pow((ptArray[i + 1].x - ptArray[i].x), 2));
                    if (0 == tempSpeed)
                    {
                        tempDirection = PS.RollDirection;
                    }
                    else
                    {
                        tempCos = (ptArray[i + 1].x - ptArray[i].x) / tempSpeed;
                        tempSin = (ptArray[i + 1].y - ptArray[i].y) / tempSpeed;
                        if (1==tempCos)
                        {
                            tempDirection = 0;
                        }
                        else if (-1==tempCos)
                        {
                            tempDirection = 180;
                        }
                        else
                        {
                            tempDirection = Math.Atan(-tempCos / Math.Sqrt(-tempCos * tempCos + 1)) + 2 * Math.Atan(1);
                            tempDirection = tempDirection * 180 / 3.1415926;
                        }
                    }
                    if (tempSin<0)
                    {
                        tempDirection = 360 - tempDirection;
                    }
                    tempError = tempDirection - PS.RollDirection;
                    if (tempError<0)
                    {
                        tempError = 360 + tempError;
                    }
                    //计算结束，开始速度检查
                    if (((tempSpeed > PS.MaxSpeed) && (tempSpeed <5 )) || (tempSpeed < PS.MinSpeed))
                    {
                        IFeatureLayer pFeatureLayer;
                        IGeometry pGeometry;
                        ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                        IPolygon pPolygon;
                        IPointCollection pPointCollection = new Polygon();
                        object Missing = Type.Missing;
                        IPoint pPoint1 = new PointClass();
                        pPoint1.X = ptArray[i].x - tempSin * PS.RollWidth / 2;
                        pPoint1.Y = ptArray[i].y + tempCos * PS.RollWidth / 2;
                        pPointCollection.AddPoint(pPoint1, ref Missing, ref Missing);
                        IPoint pPoint2 = new PointClass();
                        pPoint2.X = ptArray[i].x + tempSin * PS.RollWidth / 2;
                        pPoint2.Y = ptArray[i].y - tempCos * PS.RollWidth / 2;
                        pPointCollection.AddPoint(pPoint2, ref Missing, ref Missing);
                        IPoint pPoint3 = new PointClass();
                        pPoint3.X = pPoint1.X + tempSpeed * tempCos;
                        pPoint3.Y = pPoint1.Y + tempSpeed * tempSin;
                        pPointCollection.AddPoint(pPoint3, ref Missing, ref Missing);
                        IPoint pPoint4 = new PointClass();
                        pPoint4.X = pPoint2.X + tempSpeed * tempCos;
                        pPoint4.Y = pPoint2.Y + tempSpeed * tempSin;
                        pPointCollection.AddPoint(pPoint4, ref Missing, ref Missing);
                        pPolygon = pPointCollection as IPolygon;
                        pGeometry = pPolygon as IGeometry;
                        pSpatialFilter.Geometry = pGeometry;
                        pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
                        pFeatureLayer = axMapControl1.get_Layer(0) as FeatureLayer;
                        IFeatureSelection pSelection;
                        pSelection = pFeatureLayer as IFeatureSelection;
                        pSelection.SelectFeatures(pSpatialFilter, esriSelectionResultEnum.esriSelectionResultNew, true);
                        ISelectionSet pSelectionSet;
                        pSelectionSet = pSelection.SelectionSet;
                        IFields pFields;
                        for(int j=0;j<pSelectionSet.Count;j++)
                        {
                            IEnumIDs ids = pSelectionSet.IDs;
                            long id = ids.Next();
                            //MessageBox.Show(id.ToString());
                            SDDetect.GridStatus[(int)id].speed += 1;     // SDDetect.GridStatus[(int)id].speed + "2";
                        }                    
                    
                    }
                    //开始方向检查

                }             int b = Environment.TickCount; MessageBox.Show((b - a).ToString());
                MessageBox.Show("cal down");
                //开始显示的实验
                form5.progressBar1.Value = 0;
                form5.progressBar1.Maximum = pFeatureClass.FeatureCount(null); ;
                IFeatureCursor pFC = pFeatureClass.Search(null,false);
                IFeature pFeature = pFC.NextFeature();
                int value=0;
                while (pFeature != null)
                {
                    form5.progressBar1.Value += 1;
                    value = SDDetect.GridStatus[Convert.ToInt32(pFeature.get_Value(2))].speed;
                    pFeature.set_Value(pFeatureClass.FindField("超速次数"),value.ToString());
                    pFeature.Store();
                    pFeature = pFC.NextFeature();
                }
/*
                for (int i = 54000; i < 60000; i++)
                {
                    form5.progressBar1.Value = i;
                    System.Diagnostics.Trace.WriteLine(i);
                    if (SDDetect.GridStatus[i].speed == 0)
                        ;// pFeatureClass.GetFeature(i).set_Value(pFeatureClass.FindField("超速次数"), "0");
                    else if (1 == SDDetect.GridStatus[i].speed)
                    {
                        pFeatureClass.GetFeature(i).set_Value(pFeatureClass.FindField("超速次数"), "1");
                        pFeatureClass.GetFeature(i).Store();
                    }
                    else if (2 == SDDetect.GridStatus[i].speed)
                    {
                        pFeatureClass.GetFeature(i).set_Value(6, "2");
                        pFeatureClass.GetFeature(i).Store();
                    }
                    else
                    {
                        pFeatureClass.GetFeature(i).set_Value(6, "3");
                        pFeatureClass.GetFeature(i).Store();
                    }
                    //if (SDDetect.GridStatus[i].direction == null)
                    //    pFeatureClass.GetFeature(i).set_Value(pFeatureClass.FindField("偏向次数"), "0");
                    //else if (1 == SDDetect.GridStatus[i].direction.Length)
                    //    pFeatureClass.GetFeature(i).set_Value(pFeatureClass.FindField("偏向次数"), "1");
                    //else if (2 == SDDetect.GridStatus[i].direction.Length)
                    //    pFeatureClass.GetFeature(i).set_Value(pFeatureClass.FindField("偏向次数"), "2");
                    //else
                    //    pFeatureClass.GetFeature(i).set_Value(pFeatureClass.FindField("偏向次数"), "3");

                }
                MessageBox.Show("begindraw");
*/
                // draw
                IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();

                IRgbColor pRGB = new RgbColorClass();
                pRGB.RGB = 255;
                IColor pColor = pRGB as IColor;
                ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbolClass();
                pSimpleFillSymbol.Color = pColor;
                pSimpleFillSymbol.Outline.Color = pColor;
                pSimpleFillSymbol.Outline.Width = 0.4;
                pSimpleFillSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                ISymbol pSymbol = pSimpleFillSymbol as ISymbol;
                pUniqueValueRenderer.AddValue("3", "3", pSymbol);

                pRGB.RGB = 128;
                pColor = pRGB as IColor;
                pSimpleFillSymbol.Color = pColor;
                pSimpleFillSymbol.Outline.Color = pColor;
                pSimpleFillSymbol.Outline.Width = 0.4;
                pSimpleFillSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                pSymbol = pSimpleFillSymbol as ISymbol;
                pUniqueValueRenderer.AddValue("2", "2", pSymbol);

                pRGB.RGB = 64;
                pColor = pRGB as IColor;
                pSimpleFillSymbol.Color = pColor;
                pSimpleFillSymbol.Outline.Color = pColor;
                pSimpleFillSymbol.Outline.Width = 0.4;
                pSimpleFillSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                pSymbol = pSimpleFillSymbol as ISymbol;
                pUniqueValueRenderer.AddValue("1", "1", pSymbol);

                pRGB.RGB = 150;
                pColor = pRGB as IColor;
                pSimpleFillSymbol.Color = pColor;
                pSimpleFillSymbol.Outline.Color = pColor;
                pSimpleFillSymbol.Outline.Width = 0.4;
                pSimpleFillSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                pSymbol = pSimpleFillSymbol as ISymbol;
                pUniqueValueRenderer.DefaultSymbol = pSymbol;
                pUniqueValueRenderer.UseDefaultSymbol = true;
                

                pUniqueValueRenderer.FieldCount = 1;
                pUniqueValueRenderer.set_Field(0, "超速次数");
                IFeatureLayer pFLayer = axMapControl1.get_Layer(0) as IFeatureLayer;
                IGeoFeatureLayer pGeoFeatureLayer = pFLayer as IGeoFeatureLayer;
                pGeoFeatureLayer.Renderer = pUniqueValueRenderer as IFeatureRenderer;
                //        axMapControl1.FullExtent = true;
                axMapControl1.Refresh();
               

            }
                    
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //连接数据库
            bool flag = false;//过程判断变量
            DBConnection DBC = DBConnection.Instance();
            Paraseting PS = Paraseting.Instance();  ////常规设置保存的若干变量,,详见DBConnection.cs
            if (PS.UnitNo == null || PS.UnitNo.Length == 0)
                MessageBox.Show("未选择层号或场号,请点击\"常规设置\"进行先择");
            else
            {
                ///
                ///根据CHECK表判断该层是否计算
                ///
                DBOperation DBO_check = new DBOperation();
                DBO_check.ConnectionString = DBC.ConnectionString;
                SqlConnection conn_check = DBO_check.Connect();
                string str_check = @"SELECT Status FROM GPSTBL_H_CHECK WHERE (FieldNo = '" + PS.UnitNo + "')";
                //MessageBox.Show(str_check);
                SqlCommand cmd_chek = new SqlCommand(str_check, conn_check);
                SqlDataReader dr_check = cmd_chek.ExecuteReader();


                FieldInitial FI = FieldInitial.CtInstance();
                if (!dr_check.Read())
                {
                    MessageBox.Show("该层数据尚未计算,点击\"确定\"进行计算");
                    FieldCalculation FC = new FieldCalculation();
                    //DateTime dt1, dt2;
                    //dt1 = DateTime.Now;
                    FC.Elevation_Calculation(PS.UnitNo,PS.Point_Range,PS.Point_Grid_Range,this);
                    FC.Elevation_UpdateDB(PS.UnitNo);
                    if(FC.UpdataDB)
                    {
                        DBOperation DBO_update=new DBOperation();
                        DBO_update.ConnectionString = DBC.ConnectionString;
                        SqlConnection conn_update = DBO_update.Connect();
                        string str_update = @"INSERT INTO GPSTBL_H_CHECK (FieldNo, Status) VALUES(" + PS.UnitNo + @",1)";
                        SqlCommand cmd_update=new SqlCommand(str_update,conn_update);
                        cmd_update.ExecuteNonQuery();
                        DBO_update.CloseConnection();
                    }
                    FI.CurrentInitial(PS.UnitNo);
                    

                    //dt2 = DateTime.Now;
                    //MessageBox.Show((dt2 - dt1).ToString());
                        
                }
                else
                {
                    if (Convert.ToInt32(dr_check.GetValue(0)) == 1)
                    {
                        MessageBox.Show("该层结果已存在，请选择评价项查看结果！");
                        FI.CurrentInitial(PS.UnitNo);
                    }
                }
                conn_check.Close();
                this.radioButton1.Enabled = true;
                this.radioButton2.Enabled = true;
                this.radioButton3.Enabled = true;
                this.radioButton4.Enabled = true;
                this.listBox1.Enabled = true;
                /*this.dispixturebox.Top = this.axMapControl1.Top;
                this.dispixturebox.Left = this.axMapControl1.Left;
                this.dispixturebox.Size = this.axMapControl1.Size;
                this.axMapControl1.Visible = false;
                this.dispixturebox.Visible = true;

                IPoint pt = new PointClass();
                IPoint pt1 = new PointClass();
                pt = this.axMapControl1.ToMapPoint(this.axMapControl1.Left, this.axMapControl1.Top);
                pt1.X = pt.X + 0.25;
                pt1.Y = pt.Y + 0.25;
                int  tempX=0, tempY=0,tempX1=0,tempY1=0;
                this.axMapControl1.FromMapPoint(pt,ref tempX,ref tempY);
                this.axMapControl1.FromMapPoint(pt1, ref tempX1, ref tempY1);
                FI.pt = pt;
                pt = this.axMapControl1.ToMapPoint(this.axMapControl1.Left+1, this.axMapControl1.Top+1);
                FI.Xextent = pt.X - FI.pt.X;
                FI.Yextent = FI.pt.Y-pt.Y;
                FI.x25 = tempX1 - tempX;
                FI.y25 = tempY - tempY1;
                MessageBox.Show(FI.x25.ToString());*/
            }
            //////////////////
            

         }

        private void radioButton1_Click(object sender, EventArgs e)
        {
            /*FieldInitial fi = FieldInitial.CtInstance();
            this.listBox1.Items.Clear();
            int left = this.dispixturebox.Left;
            int top = this.dispixturebox.Top;
            //MessageBox.Show(fi.Xextent.ToString());
            this.groupBox5.Text = "平整度区间选择(m)";
            this.listBox1.Items.Add(" 0.05");
            this.listBox1.Items.Add(" 0.04");
            this.listBox1.Items.Add(" 0.03");
            this.listBox1.Items.Add(" 0.02");
            this.listBox1.Items.Add(" 0.01");
            this.listBox1.Items.Add(" "+fi.averageh.ToString());
            this.listBox1.Items.Add(" -0.01");
            this.listBox1.Items.Add(" -0.02");
            this.listBox1.Items.Add(" -0.03");
            this.listBox1.Items.Add(" -0.04");
            this.listBox1.Items.Add(" -0.05");
            this.listBox1.SetSelected(5,true);

            Graphics g = this.dispixturebox.CreateGraphics();
            g.Clear(this.dispixturebox.BackColor);
            SolidBrush redBrush = new SolidBrush(Color.Red);
            SolidBrush greenBrush = new SolidBrush(Color.Green);
            for(int i=0;i<fi.GridCount;i++)
            {
                if(Math.Abs(fi.mCurrentGrid[i].Lh-fi.averageh)<=0.01)
                    g.FillEllipse(redBrush,(float)((fi.mCurrentGrid[i].X-fi.pt.X)/fi.Xextent+left-fi.x25),(float)((fi.pt.Y-fi.mCurrentGrid[i].Y)/fi.Yextent+top-fi.y25),4,4);
                else
                    g.FillEllipse(greenBrush,(float)((fi.mCurrentGrid[i].X - fi.pt.X) / fi.Xextent+ left-fi.x25),(float)((fi.pt.Y-fi.mCurrentGrid[i].Y)/fi.Yextent+top-fi.y25), 4, 4);
            }*/
            FieldInitial fi = FieldInitial.CtInstance();
            this.groupBox5.Text = "平整度区间选择(m)";
            this.listBox1.Items.Add(" 0.05");
            this.listBox1.Items.Add(" 0.04");
            this.listBox1.Items.Add(" 0.03");
            this.listBox1.Items.Add(" 0.02");
            this.listBox1.Items.Add(" 0.01");
            this.listBox1.Items.Add(" " + fi.averageh.ToString());
            this.listBox1.Items.Add(" -0.01");
            this.listBox1.Items.Add(" -0.02");
            this.listBox1.Items.Add(" -0.03");
            this.listBox1.Items.Add(" -0.04");
            this.listBox1.Items.Add(" -0.05");
            this.listBox1.SetSelected(5, true);

        }

        

        private void button5_Click(object sender, EventArgs e)
        {
            DBConnection DBC = DBConnection.Instance();
            DBOperation DBO = new DBOperation();
            DBO.ConnectionString = DBC.ConnectionString;
            SqlConnection conn = DBO.Connect();
            string str_cmd = @"SELECT Status FROM GPSTBL_CHECK WHERE (FieldNo = '74841')";
            try
            {
                SqlCommand cmd = new SqlCommand(str_cmd, conn);
                SqlDataReader dr = cmd.ExecuteReader();
                if (!dr.Read())
                    MessageBox.Show("not check");
                else
                    MessageBox.Show(dr.GetValue(0).ToString());
                //MessageBox.Show(cmd.ExecuteScalar().ToString());
            }
            catch
            {
                MessageBox.Show("null");
            }
            
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string strconn = "Data Source=USER;Initial Catalog=GPSDBNew;Integrated Security=SSPI";
            SqlConnection conn = new SqlConnection(strconn);
            conn.Open();
            SqlCommand cmd = new SqlCommand("select * from dbo.TBLGPSDATA_1000_133_74961_5", conn);

            IPoint pPoint = new PointClass();
            SqlDataReader dr = cmd.ExecuteReader();
            dr.Read();
            pPoint.X = Convert.ToDouble(dr.GetValue(7));
            pPoint.Y = Convert.ToDouble(dr.GetValue(8));
            this.axMapControl1.ActiveView.ScreenDisplay.DrawPoint((IGeometry)pPoint);
        }

        public AxMapControl MapControl
        {
            get { return axMapControl1; }
            set { axMapControl1 = value;}
        }

        private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            IFeatureWorkspace pFWS;
            IWorkspaceFactory pWSF = new ShapefileWorkspaceFactory();
            pFWS = pWSF.OpenFromFile(System.Windows.Forms.Application.StartupPath+@"\图层数据", 0) as IFeatureWorkspace;
            IFields pFields = new FieldsClass();
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;
            IField pField = new FieldClass();
            IFieldEdit pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Name_2 = "Shape";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

            IGeometryDef pGeometryDef = new GeometryDefClass();
            IGeometryDefEdit pGEoDefEdit = pGeometryDef as IGeometryDefEdit;
            pGEoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            pFieldEdit.GeometryDef_2 = pGEoDefEdit;
            pFieldsEdit.AddField(pField);

            IFeatureLayer pClipFeature = new FeatureLayerClass();
            pClipFeature.Name = "Mask";

            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null;
            fieldChecker.ValidateWorkspace = (IWorkspace)pFWS;
            fieldChecker.Validate(pFields, out enumFieldError, out validatedFields);

            pClipFeature.FeatureClass = pFWS.CreateFeatureClass("Mask", pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
            IFeatureCursor pFeatureCursor = pClipFeature.FeatureClass.Insert(true);
            IFeatureBuffer pBuffer = pClipFeature.FeatureClass.CreateFeatureBuffer();

            //创建多边形
            IPolygon pPolygon = new PolygonClass();
            pPolygon = axMapControl1.TrackPolygon() as IPolygon;
            IGeometry pGeometry = pPolygon as IGeometry;

            pBuffer.Shape = pGeometry;
            pFeatureCursor.InsertFeature(pBuffer);
            pFeatureCursor.Flush();

            //将Mask图层加入shapefile
            axMapControl1.AddLayer((ILayer)pClipFeature); axMapControl1.get_Layer(1).Visible = false;

            Geoprocessor BGP = new Geoprocessor();
            Clip pClip = new Clip();
            pClip.in_features = axMapControl1.get_Layer(1);
            pClip.clip_features = axMapControl1.get_Layer(0);
            pClip.out_feature_class = System.Windows.Forms.Application.StartupPath+@"\图层数据\MainGrid.shp";
            BGP.Execute(pClip, null);

            MessageBox.Show("clipover");
            axMapControl1.get_Layer(0).Visible = false; 
            MessageBox.Show("clipover");
            axMapControl1.AddShapeFile(System.Windows.Forms.Application.StartupPath+@"\图层数据","MainGrid.shp");
            IActiveView pActiveView = axMapControl1.ActiveView;
            pActiveView.Extent = axMapControl1.FullExtent;
            pActiveView.Refresh();
            axMapControl1.Enabled = true; 
            MessageBox.Show("clipover");

        }

        private void 删除当前层记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DBConnection DBC = DBConnection.Instance();
            Paraseting PS = Paraseting.Instance();////常规设置保存的若干变量,,详见DBConnection.cs
            if((PS.UnitNo==null)||(PS.UnitNo.Length!=5))
            {
                MessageBox.Show("层号或场号选择错误!");
                return;
            }
            try
            {
                DBOperation DBO = new DBOperation();
                DBO.ConnectionString = DBC.ConnectionString;
                SqlConnection conn = DBO.Connect();
                string str_cmd = @"DELETE FROM GPSTBL_H_CHECK WHERE (FieldNo = '" + PS.UnitNo + @"')";
                SqlCommand cmd = new SqlCommand(str_cmd, conn);
                cmd.ExecuteNonQuery();
                str_cmd = @"DROP TABLE GPSTBL_H_" + PS.UnitNo.Insert(4, "_");
                cmd.CommandText = str_cmd;
                cmd.ExecuteNonQuery();
                DBO.CloseConnection();
            }
            catch
            {
                MessageBox.Show("数据库连接异常,请与管理员联系!");
            }
            
        }

        

        
        

        

        

        
        
   

    }
}
